<template>
  <section>
    <a-modal
      v-if="isModalView"
      width="800px"
      v-model="showAddressModal"
      destroyOnClose
      centered
      title="点击地图定位"
      @ok="submitOk"
      @cancel="cancel"
    >
      <template #closeIcon>
        <section class="mt-10 mr-20 flex items-start justify-end px-4 pt-8">
          <a-icon type="close"/>
        </section>
      </template>
      <section class="mb-10 flex">
        <a-input disabled v-model="address" allowClear :maxLength="100" placeholder="请输入详细地址"/>
      </section>
      <div ref="map" :style="{height}"/>
    </a-modal>
    <div v-else ref="map" :style="{height}"/>
  </section>
</template>
<script>
import AMap from 'AMap'

export default {
  name: 'AddressComp',
  props: {
    height: {
      type: String,
      default: '400px'
    },
    isModalView: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      showAddressModal: false,
      aMap: null,
      pin: require('@/assets/icons/pin.png'),
      address: null,
      marker: null,
      data: null,
      type: 0
    }
  },
  methods: {
    submitOk() {
      if (!this.data) return this.$message.warning('请选择地址')
      this.$emit('uploadPoint', {...this.data, type: this.type})
      this.cancel()
    },
    cancel() {
      this.data = null
      this.aMap = null
      this.showAddressModal = false
    },
    setMapPoint(data) {
      const {longitude, latitude, address} = data
      this.initAMap()
      if (this.marker) this.aMap.remove(this.marker)
      this.$nextTick(() => {
        const position = [longitude, latitude]
        this.aMap.setCenter(position, true, 0)
        this.marker = new AMap.Marker({
          position,
          icon: this.pin,
          anchor: 'bottom-center',
          offset: new AMap.Pixel(0, 0)
        })
        this.marker.setMap(this.aMap)
        this.marker.setLabel({
          direction: 'top',
          offset: new AMap.Pixel(0, -10),
          content: address
        })
        this.data = data
      })
    },
    showInfoClick(e) {
      if (!this.isModalView) return
      const lng = e.lnglat.getLng()
      const lat = e.lnglat.getLat()
      this.getAddress([lng, lat])
      if (e.keyCode === 13) {
        regeoCode()
        return false
      }
      return true
    },
    //根据经纬度获取地址
    getAddress(data) {
      this.geocoder.getAddress(data, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.address = result.regeocode.formattedAddress
          this.setMapPoint({address: this.address, longitude: data[0], latitude: data[1]})
        } else {
          console.error('根据经纬度查询地址失败')
        }
      })
    },
    // 获取搜索信息
    getAddressValue(data) {
      const {address,type} = data
      if (type) this.type = type
      this.address = address
      this.showAddressModal = true
      this.$nextTick(() => {
        this.initAMap()
        AMap.plugin('AMap.Geolocation', () => {
          let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            buttonPosition: 'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true   //定位成功后是否自动调整地图视野到定位点
          });
          this.aMap.addControl(geolocation)
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          })
        })
        //解析定位结果
        const onComplete = (data) => {
          const {lng, lat} = data.position
          this.getAddress([lng, lat])
        }

        //解析定位错误信息
        const onError=(data)=>{
          this.$message.warning('自动定位失败，请点击地图选择')
        }
      })
    },
    initAMap() {
      if (!this.aMap) {
        this.aMap = new AMap.Map(this.$refs.map, {
          resizeEnable: true,
          zoom: 16
        })
        this.aMap.on('complete', () => {
          this.geocoder = new AMap.Geocoder()
          this.aMap.on('click', this.showInfoClick)
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
  /deep/ .amap-markers {
    .amap-icon {
      img {
        width: 25px;
        height: 25px;
      }
    }

    .amap-marker-label {
      position: absolute;
      z-index: 2;
      border: none;
      background-color: #fff;
      white-space: nowrap;
      cursor: default;
      padding: 10px 12px;
      font-size: 14px;
      line-height: 14px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, .15);
      border-radius: .25rem;
    }
  }
</style>
